<!--
 * @Description:
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-08-16 16:45:52
 * @LastEditTime: 2022-06-07 16:41:01
 * @FilePath: \cscec-pms-admin\src\views\project\optimization\index.vue
-->
<template>
  <base-breadcrumb :title="titleName">
    <searchData
      :search-data="searchArr"
      @search="search"
    />
    <a-card :bordered="false">
      <!-- <title-name title="双优化立项列表" /> -->
      <list-table
        ref="table"
        size="default"
        :columns="columns"
        :request="loadData"
        :startIndex="0"
        row-key="optimizationId"
        :export-config="{ use: true, select: '双优化立项列表', all: '双优化立项列表',customColumns: customColumns}"
        :export-permission="{select: 'tm_004_loo_04',all: 'tm_004_loo_04'}"
        :statistics-config="{ use: true, totalDels, temp }"
        :out-selected-row-keys.sync="outSelectedRowKeys"
      >
        <template
          v-if="!isCopyInDesigns"
          slot="prefix"
        >
          <a-button
            v-btnPermission="[{code:'seex_tm_004_add_01',ident:'prma_seex'},{code:'buco_tm_004_add_01',ident:'prma_buco'}]"
            type="primary"
            @click="handleAdd"
            v-if="hideBuquBtn()"
          >
            新增双优化立项
          </a-button>
          <a-button
            v-btnPermission="[{code:'seex_tm_004_pro_07',ident:'prma_seex'},{code:'buco_tm_004_pro_07',ident:'prma_buco'}]"
            type="primary"
            icon="download"
            :disabled="outSelectedRowKeys.length===0"
            @click="handlePushExcellent"
            v-if="hideBuquBtn()"
          >
            选中推优
          </a-button>
        </template>
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>

        <!-- <span
          slot="type"
          slot-scope="text, record"
        >
          <span v-if="record.type== '111'">设计优化</span>
          <span v-if="record.type== '222'">施工组织设计(方案)优化</span>
        </span> -->
        <template
          slot="status"
          slot-scope="text"
        >
          <a-badge
            :status="text | statusTypeFilter"
            :text="text | statusFilter"
          />
        </template>
        <template
          slot="description"
          slot-scope="text"
        >
          <ellipsis
            :length="8"
            tooltip
          >
            {{ text }}
          </ellipsis>
        </template>
        <template
          slot="action"
          slot-scope="text, record"
        >
          <MoreButton>
            <a @click="handleDels(record)" v-btn-permission="'tm_004_loo_04'">查看</a>
            <template v-if="!isCopyInDesigns">
              <template v-if="record.statusCode ==0 ||record.statusCode ==3 ">
                <a
                  v-btnPermission="[{code:'seex_tm_004_edi_02',ident:'prma_seex'},{code:'buco_tm_004_edi_02',ident:'prma_buco'}]"
                  @click="handleEdit(record)"
                >编辑</a>
              </template>
            </template>
            <template v-if="record.statusCode=='1' || record.statusCode=='2' ||record.statusCode=='3' ">
              <a @click="handleApproveDetail(record)" v-btn-permission="'tm_004_moi_05'">审批信息</a>
            </template>
            <template
              v-if="record.statusCode=='2'"
              v-btnPermission="[{code:'seex_tm_004_loo_04',ident:'prma_seex'},{code:'buco_tm_004_loo_04',ident:'prma_buco'}]"
            >
              <BasePrintButton
                button-type="a"
                :before-print-fn="()=>handlePrint(record)"
              />
            </template>
          </MoreButton>
        </template>
      </list-table>

      <ApprovalDetails
        :title="'审批详情'"
        :business-id="businessId"
        :visible="visibleApprove"
        @cancel="visibleApprove = false"
        @confirm="visibleApprove = false"
      />
    </a-card>
  </base-breadcrumb>
</template>

<script>
import moment from 'moment'
import { Ellipsis } from '@/components'
import { getOptimizationList, getOptimizationTotal, optimization, recommend } from '@/api/project/optimization'
import { getTechnicalTypes } from '@/api/commons'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject'
import OrgTreeSelect from '@/components/OrgTreeSelect'
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
import ApprovalDetails from '@/components/approvalDetails'
import ARow from 'ant-design-vue/es/grid/Row'
import Excel from 'exceljs'
import { forEach } from 'store/storages/all'
const columns = [
  {
    title: '序号',
    width: '65px',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '双优化立项编号',
    dataIndex: 'optimizationNum'
  },
  {
    title: '双优化立项名称',
    dataIndex: 'optimizationName'
  },
  {
    title: '实施项目',
    dataIndex: 'projectName'
  },
  {
    title: '分公司',
    dataIndex: 'branch'
  },
  {
    title: '优化类型',
    dataIndex: 'typeName'
  },
  {
    title: '详细分类',
    dataIndex: 'classification'
  },
  {
    title: '计划实施时间',
    dataIndex: 'startTime'
  },
  {
    title: '计划结束时间',
    dataIndex: 'endTime'
  },
  {
    title: '提出人',
    dataIndex: 'proposer'
  },
  {
    title: '拟实施人',
    dataIndex: 'implementer'
  },
  {
    title: '预测增效效益',
    dataIndex: 'increaseBenefit'
  },
  {
    title: '预测减亏效益',
    dataIndex: 'reduceBenefit'
  },
  {
    title: '优化类别',
    dataIndex: 'optimizeStageName'
  },
  {
    title: '立项效益(万元)',
    dataIndex: 'forecastBenefit'
  },
  {
    title: '项目业态',
    dataIndex: 'projectFormatName'
  },
  {
    title: '项目设计管理类别',
    dataIndex: 'designName'
  },
  {
    title: '专业类别',
    dataIndex: 'professionalTypeName'
  },
  {
    title: '设计阶段',
    dataIndex: 'designStageName'
  },
  {
    title: '工程类别',
    dataIndex: 'projectType'
  },
  {
    title: '分部',
    dataIndex: 'part'
  },
  {
    title: '创新',
    dataIndex: 'isNew'
  },
  // {
  //   title: '预测减亏效益(万元)',
  //   dataIndex: 'reduceBenefit'
  // },
  // {
  //   title: '预测增效效益(万元)',
  //   dataIndex: 'increaseBenefit'
  // },
  {
    title: '状态',
    width: '110px',
    dataIndex: 'statusName'
  },
  {
    title: '是否推优',
    width: '110px',
    dataIndex: 'recommendName'
  },
  {
    title: '操作',
    dataIndex: 'actions',
    width: '200px',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'a' + Date.now(),
  components: {
    Ellipsis,
    ApprovalDetails,
    BasePrintButton
  },
  data() {
    this.columns = columns
    return {
      isCopyInDesigns: location.href.includes('designs'), //是否是复制到设计中，如果是直接把操作按钮false掉

      // 导出表头
      customColumns: [
        {
          title: '双优化立项编号',
          dataIndex: 'optimizationNum',
        },
        {
          title: '优化类型',
          dataIndex: 'typeName'
        },
        {
          title: '详细分类',
          dataIndex: 'classification'
        },
        {
          title: '施工组织设计(方案)优化',
          dataIndex: 'constructionOrganization',
        },
        {
          title: '优化类型及简要内容',
          dataIndex: 'contentDels',
        },
        {
          title: '工程名称',
          dataIndex: 'projectName',
        },
        {
          title: '优化项名称',
          dataIndex: 'optimizationName',
        },
        {
          title: '优化建议提出人',
          dataIndex: 'proposer',
        },
        {
          title: '拟实施人',
          dataIndex: 'implementer',
        },
        {
          title: '预测增效效益',
          dataIndex: 'increaseBenefit',
        },
        {
          title: '预测减亏效益',
          dataIndex: 'reduceBenefit',
        },
        {
          title: '优化类别',
          dataIndex: 'optimizeStageName',
        },
        {
          title: '立项效益(万元)',
          dataIndex: 'forecastBenefit',
        },
        {
          title: '项目业态',
          dataIndex: 'projectFormatName',
        },
        {
          title: '项目设计管理类别',
          dataIndex: 'designName',
        },
        {
          title: '专业类别',
          dataIndex: 'professionalTypeName',
        },
        {
          title: '设计阶段',
          dataIndex: 'designStageName',
        },
        {
          title: '工程类别',
          dataIndex: 'projectType',
        },
        {
          title: '分部',
          dataIndex: 'part',
        },
        {
          title: '创新',
          dataIndex: 'isNew',
        },
        {
          title: '预计优化效益及测算依据',
          dataIndex: 'calculationBasis',
        },
        {
          title: '预计优化效益',
          dataIndex: 'forecastBenefit',
        },
        {
          title: '分公司名称',
          dataIndex: 'branch',
        },
        {
          title: '最后处理人',
          dataIndex: 'finalApprovalPerson',
        },
        {
          title: '最后处理时间',
          dataIndex: 'finalApprovalTime',
        },
        {
          title: '审批状态',
          dataIndex: 'statusName',
        }
      ],
      businessId: '',
      visibleApprove: false,

      searchArr: [
        // 搜索框
        {
          name: '双优化立项名称',
          value: 'optimizationName',
          type: 'input'
        },
        {
          name: '优化类型 ',
          value: 'type',
          type: 'select',
          data: [
            { label: '设计优化', value: '111' },
            { label: '施工组织设计(方案)优化', value: '222' }
          ]
        },
        {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect,
        },
        // {
        //   name: '分公司',
        //   valueKey: 'branch',
        //   type: SelectSubCompany
        // },
        // {
        //   name: '实施项目',
        //   keyValue: 'searchQuery._checked',
        //   valueKey: 'branch',
        //   type: SelectProject
        // },
        {
          name: '状态',
          value: 'statusCode',
          type: 'select',
          data: [
            { label: '待提交审核', value: '0' },
            { label: '审核中', value: '1' },
            { label: '审核通过', value: '2' },
            { label: '审核不通过', value: '3' }
          ]
        },
        {
          name: '是否推优',
          value: 'recommend',
          type: 'select',
          data: [
            { label: '否', value: '0' },
            { label: '是', value: '1' }
          ]
        }
      ],
      titleName: '',

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log(requestParameters)
        this.getOptimizationTotal()
        return getOptimizationList(requestParameters).then((res) => {
          return res
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      totalDels: {},
      temp: () => {
        return (
            <span style="margin-right: 12px">
              双优化立项总数：<span class="totalNum">{ this.totalDels.total || 0 } 个</span> |
              待提交审核：<span class="totalNum">{this.totalDels.beReviewNum || 0 } 个</span> |
              审核中：<span class="totalNum">{ this.totalDels.underReviewNum || 0 } 个</span> |
              审核通过：<span class="totalNum">{ this.totalDels.approveNum || 0 } 个</span> |
              审核不通过：<span class="totalNum">{ this.totalDels.unapproveNum || 0 } 个</span> |
              立项效益共计：<span class="totalNum">{ this.totalDels.forecastBenefitNum || 0 } 万</span>
              {/* 预测减亏效益共计：<span class="totalNum">{ this.totalDels.reduceBenefitNum || 0 } 万</span> |
              预测增效效益共计：<span class="totalNum">{ this.totalDels.increaseBenefitNum || 0 } 万</span> */}
            </span>
          // 审批通过的项目设计优化目标指标：<span class="totalNum">{this.statistics.pastOptimizeTarget || 0} 万</span>
        )
      },
      outSelectedRowKeys: []
    }
  },
  created() {

  },
  computed: {
    // rowSelection() {
    //   return {
    //     selectedRowKeys: this.selectedRowKeys,
    //     selectedRows: this.selectedRows,   // 当前行所有数据
    //     onChange: this.onSelectChange
    //   }
    // }
  },
  methods: {
    handleApproveDetail(record) {
      this.visibleApprove = true
      this.businessId = record.optimizationId
    },
    search(val) {
      this.queryParam = val
      this.$refs.table.refresh(true)
      // this.getOptimizationTotal()
    },

    getOptimizationTotal() {
      getOptimizationTotal(this.queryParam).then((res) => {
        this.totalDels = res.data
      })
    },

    handleDels(val) {
      this.$router.push({ path: '/project/optimization/details', query: { id: val.optimizationId } })
    },

    handleAdd() {
      this.$router.push({ path: '/project/addOptimization', query: { isEdit: 0 } })
    },
    /**
     * @description: 选中推优
     * @param {void}
     * @return {void}
     */
    handlePushExcellent() {
      const vm = this
      vm.$confirm({
        title: `审批通过后的立项数据可进行推优`,
        okText: '确认',
        okType: 'primary',
        cancelText: '取消',
        type: 'warning',
        async onOk() {
          const {
            data: { code, message }
          } = await recommend({ idList: vm.outSelectedRowKeys })
          if (code === 200) {
            vm.outSelectedRowKeys = []
            vm.$message.success('操作成功')
            vm.$refs.table.refresh(true)
          } else {
            vm.$message.success(message)
          }
        }
      })
    },
    handleEdit(val) {
      this.$router.push({ path: '/project/editOptimization', query: { id: val.optimizationId, isEdit: 1 } })
    },

    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    /**
     * @description: 打印
     * @param {void}
     * @return {void}
     */
    handlePrint(record) {
      return optimization({ businessId: record.optimizationId }).then(({ data: { content } }) => {
        return content
      })
    },
    /**
     * @description: 选中导出
     * @param {void}
     * @return {void}
     */
    async exportSelect(e) {
      this.exportExcel(e)
    },
    /**
     * @description: 导出全部
     * @param {void}
     * @return {void}
     */
    exportAll(e) {
      this.exportExcel(e)
    },
    async exportExcel(e) {
      const wb = new Excel.Workbook()
      const sheet = wb.addWorksheet('asd')
      sheet.columns = [
        {
          header: '双优化立项编号',
          key: 'optimizationNum',
          width: 30,
        },
        {
          header: '设计优化',
          key: 'designOptimization',
          width: 30
        },
        {
          header: '施工组织设计(方案)优化',
          key: 'constructionOrganization',
          width: 30
        },
        {
          header: '优化类型及简要内容',
          key: 'contentDels',
          width: 30
        },
        {
          header: '工程名称',
          key: 'projectName',
          width: 20
        },
        {
          header: '优化项名称',
          key: 'optimizationName',
          width: 20
        },
        {
          header: '优化建议提出人',
          key: 'proposer',
          width: 30
        },
        {
          header: '拟实施人',
          key: 'implementer',
          width: 30
        },
        {
          title: '预测增效效益',
          key: 'increaseBenefit',
          width: 30
        },
        {
          title: '预测减亏效益',
          key: 'reduceBenefit',
          width: 30
        },
        {
          title: '优化类别',
          key: 'optimizeStageName',
          width: 30
        },
        {
          title: '立项效益(万元)',
          key: 'forecastBenefit',
          width: 30
        },
        {
          title: '项目业态',
          key: 'projectFormatName',
          width: 30
        },
        {
          title: '项目设计管理类别',
          key: 'designName',
          width: 30
        },
        {
          title: '专业类别',
          key: 'professionalTypeName',
          width: 30
        },
        {
          title: '设计阶段',
          key: 'designStageName',
          width: 30
        },
        {
          title: '工程类别',
          key: 'projectType',
          width: 30
        },
        {
          title: '分部',
          key: 'part',
          width: 30
        },
        {
          title: '创新',
          key: 'isNew',
          width: 30
        },
        {
          header: '预计优化效益及测算依据',
          key: 'calculationBasis',
          width: 30
        },
        {
          header: '预计优化效益',
          key: 'forecastBenefit',
          width: 20
        },
        {
          header: '分公司名称',
          key: 'branch',
          width: 30
        },
        {
          header: '最后处理人',
          key: 'finalApprovalPerson',
          width: 30
        },
        {
          header: '最后处理时间',
          key: 'finalApprovalTime',
          width: 30
        },
        {
          header: '审批状态',
          key: 'statusName',
          width: 30
        }
      ]
      const list = e.map((el) => {
        const item = el
        if (el.typeName === '设计优化') {
          item.designOptimization = el.classification
        }
        if (el.typeName === '施工组织设计(方案)优化') {
          item.constructionOrganization = el.classification
        }
        return item
      })
      sheet.addRows(list)
      sheet.getRow(1).font = { name: '等线', bold: true }
      // 导出
      const buffer = await wb.xlsx.writeBuffer()
      let blob = new Blob([buffer], {
        type: 'application/octet-stream'
      })

      let url = blob
      if (url instanceof Object && url instanceof Blob) {
        url = URL.createObjectURL(url) // 创建blob地址
      }
      var aLink = document.createElement('a')
      aLink.href = url
      aLink.download = '双优化立项.xlsx' // 文件名
      let event
      if (window.MouseEvent) {
        event = new MouseEvent('click')
      } else {
        event = document.createEvent('MouseEvents')
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
      }
      aLink.dispatchEvent(event)
    }
  }
}
</script>
